<?php defined('SYSPATH') or die('No direct script access.');

class Model_Competitor extends ORM
{  
    protected $_reload_on_wakeup = false;
    
    public function get_competitors(Model_Model $model)
    {
        // TODO cache, order by score
        $tmp = ORM::factory('competitor')
                ->where('model_id', '=', $model->id)
                ->find_all();
        $ids = array();
        foreach ($tmp as $row) {
            $ids[] = $row->competitor_id;    
        }
        $competitors = array();
        if (count($ids)) {
            $competitors = ORM::factory('model')
                            ->where('id', 'IN', $ids)
                            ->order_by('score', 'DESC')
                            ->find_all();
        }       
        return $competitors;
    }
    
    public function merge_competitors(Model_Model $model1, Model_Model $model2, $limit = 10)
    {
        // TODO cache, order by score
        $tmp = ORM::factory('competitor')
                ->where('model_id', 'IN', array($model1->id, $model2->id));
        if ($limit) {
            $tmp->limit($limit);    
        }
        $tmp = $tmp->find_all();
        
        $ids = array();
        foreach ($tmp as $row) {
            if ($row->competitor_id != $model1->id && $row->competitor_id != $model2->id) {
                $ids[$row->competitor_id] = $row->competitor_id;
            }    
        }
        $competitors = ORM::factory('model')
                            ->where('id', 'IN', $ids)
                            ->order_by('score', 'DESC')
                            ->find_all();       
        return $competitors;
    }
}